export default {
    state: {
        list: JSON.parse(localStorage.getItem("cart")) || []
    },
    actions: {

    },
    mutations: {
        addcart(state, item) {

            //添加商品到购物车
            const good = state.list.find(v => v.title == item.title)
            if (good) {

                good.cartCount += 1;
            } else {

                state.list.push({
                    ...item,
                    cartCount: 1
                })
            }

            localStorage.setItem('cart', JSON.stringify(state.list))
        },
        cartremove(state, index) {
            if (state.list[index].cartCount > 1) {
                state.list[index].cartCount -= 1;
            }
        },
        cartadd(state, index) {
            state.list[index].cartCount += 1;
        }
    },
    getters: {
        cartTotal: state => {
            //商品总数量
            let num = 0;
            state.list.forEach(v => {
                num += v.cartCount
            })
            return num;
        },
        total: state => {
            // return state.list.reduce((total, item) => {
            //         total += item.cartCount * item.price
            //     })
            let obj = {
                cartCount: 0,
                acount: 0
            };
            state.list.forEach(item => {
                obj.cartCount += item.cartCount;
                obj.acount += item.cartCount * item.price

            })
            return obj.acount;
        }
    }
}